//
//  HomeFooterView.m
//  YZMicroStock
//
//  Created by 王慕铁 on 2017/12/11.
//  Copyright © 2017年 cqjr. All rights reserved.
//

#import "HomeFooterView.h"
#import "YZMSegmentViewScroll.h"
#import "YZMTrendCell.h"
#import "YZMRankCell.h"
#import "YZGeneralResultModel.h"
#import "YZClient.h"
#import "YZMConfigureService.h"

#define RankCellHeight 60

static NSUInteger _index = 0;

static NSString *const home_page_trade_cell_identifier = @"YZMRankCell";
static NSString *const home_page_master_cell_identifier = @"YZMTrendCell";

@interface HomeFooterView()<UITableViewDelegate , UITableViewDataSource , YZMSegmentViewDelegate>

@property (nonatomic , strong) YZMSegmentViewScroll* segView;

@end

@implementation HomeFooterView {
    CGFloat _Y;
    
    UITableView *_tradeTV;
    UITableView *_masterTV;
    
    NSMutableArray *_rankStrategyArray;
    NSMutableArray *_rankUserArray;
    
    NSTimer *_rankTimer;
}


- (instancetype)initWithY:(CGFloat)Y {
    if (self = [super init]) {
        _Y = Y;
        self.backgroundColor = [YZMAppStyle appBackgroundColor];
        self.frame = CGRectMake(10, Y, ScreenWidth - 20, 100);
        [self NetWork];
        [self initArray];
        [self createFooterView];
    }
    return self;
}

- (void)NetWork {
    [self fetchRankListData];
    [self fetchTrendListData];
}

- (void)initArray {
    _rankStrategyArray=[NSMutableArray array];
    _rankUserArray=[NSMutableArray array];
}

- (void)createFooterView
{
    if (YZMSWitchOn) {
        self.backgroundColor = [UIColor clearColor];
        _segView = [YZMSegmentViewScroll new];
        [self addSubview:_segView];
        [_segView mas_makeConstraints:^(MASConstraintMaker *make){
            
            make.top.mas_equalTo(self.mas_top);
            make.left.right.equalTo(self);
            make.bottom.equalTo(self);
            
        }];
        _segView.delegate = self;
        [self addSubview:_segView];
        _segView.titleArray = @[@"策略榜单",@"策略动态"];
        _tradeTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1) style:UITableViewStylePlain];
        _tradeTV.backgroundColor = [UIColor redColor];
        _tradeTV.delegate = self;
        _tradeTV.dataSource = self;
        _tradeTV.backgroundView = nil;
        _tradeTV.backgroundColor = [UIColor clearColor];
        _tradeTV.scrollEnabled = NO;
        _tradeTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    
    [_tradeTV registerClass:[YZMRankCell class] forCellReuseIdentifier:home_page_trade_cell_identifier];
    
    _masterTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1) style:UITableViewStylePlain];
    _masterTV.delegate = self;
    _masterTV.dataSource = self;
    _masterTV.backgroundView = nil;
    _masterTV.backgroundColor = [UIColor clearColor];
    _masterTV.scrollEnabled = NO;
    _masterTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_masterTV registerClass:[YZMTrendCell class] forCellReuseIdentifier:home_page_master_cell_identifier];
    if (YZMSWitchOn) {
        _segView.viewArray = @[_tradeTV,_masterTV];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView == _masterTV){
        
        return 60;
        
    }else{
        
        return RankCellHeight;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(tableView==_tradeTV){
        return _rankUserArray.count;
    }else if (tableView==_masterTV){
        
        return _rankStrategyArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _tradeTV) {
        
        YZMRankCell *cell = [tableView dequeueReusableCellWithIdentifier:home_page_trade_cell_identifier forIndexPath:indexPath];
        
        YZMHomeRankListModel *rankModel = _rankUserArray[indexPath.row];
        cell.rankModel = rankModel;
        cell.indexForImgageView = indexPath.row;
        
        YZMIndexCount indexCount;
        indexCount.index = indexPath.row;
        indexCount.count = _rankUserArray.count;
        cell.indexCount = indexCount;
        cell.handle = ^{
            [YZMHCMInstance pushViewControllerWithName: @"stock" andParams: nil];
        };
        
        return cell;
    } else if (tableView == _masterTV) {
        
        YZMTrendCell *cell = [tableView dequeueReusableCellWithIdentifier:home_page_master_cell_identifier forIndexPath:indexPath];
        WS(ws)
        cell.handle = ^{
            [ws tradeWith:indexPath];
        };
        cell.numberForColor = indexPath.row;
        
        YZMHomeTrendModel *trendModel = _rankStrategyArray[indexPath.row];
        cell.trendModel = trendModel;
        
        YZMIndexCount indexCount;
        indexCount.index = indexPath.row;
        indexCount.count = _rankStrategyArray.count;
        cell.indexCount = indexCount;
        
        return cell;
    }
    return [[UITableViewCell alloc]init];
}

- (void)tradeWith:(NSIndexPath *)indexPath{
    if (indexPath.row<_rankStrategyArray.count) {
        YZMHomeTrendModel *trendModel = _rankStrategyArray[indexPath.row];
        if (trendModel.stockCode.length == 0) {
            return;
        }
        NSDictionary *param = nil;
        if (trendModel.stockName.length == 0) {
            param= @{@"stockcode":trendModel.stockCode};
        }else{
            param = @{@"stockcode":trendModel.stockCode,@"stockname":trendModel.stockName};
        }
        [YZMHCMInstance pushViewControllerWithName: @"stock" andParams: param];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (!YZMSWitchOn) {
//        NSDictionary *dic = _arrDataReview[indexPath.row];
//        [YZMHCMInstance pushViewControllerWithName:NSStringFromClass([YZDKnowledgeViewController class]) andParams:dic];
        
    }
    if (tableView == _tradeTV) {
        [YZMHCMInstance pushViewControllerWithName: @"stock" andParams: nil];
    }
    if (tableView == _masterTV) {
        if (indexPath.row<_rankStrategyArray.count) {
            YZMHomeTrendModel *trendModel = _rankStrategyArray[indexPath.row];
            if (trendModel.stockCode.length == 0) {
                return;
            }
            NSDictionary *param = nil;
            if (trendModel.stockName.length == 0) {
                param= @{@"stockcode":trendModel.stockCode};
            }else{
                param = @{@"stockcode":trendModel.stockCode,@"stockname":trendModel.stockName};
            }
            [YZMHCMInstance pushViewControllerWithName: @"stock" andParams: param];
        }
    }
}

-(void)fetchRankListData{
    
    if ([self checkNetwork]) {
        return;
    }
    
    if (YZMSWitchOn) {
        [YZClient fetchHomeRankListWithSuccess:^(NSURLSessionDataTask *task, id responseObject) {
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"endRefreshing" object:nil];
                YZMHomeRankListModel *model = topModel.data;
                [_rankUserArray removeAllObjects];
                [_rankUserArray addObjectsFromArray:(NSArray *)model];
                [self tableset];
                [self reloadView];
                self.frame = CGRectMake(10, _Y, ScreenWidth - 20, RankCellHeight * _rankUserArray.count + 60);
                [_tradeTV reloadData];
            }
        } failure:^(NSError *error) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"endRefreshing" object:nil];
            [error yz_showMessage];
            
        }];
    }else{
        
    }
}

-(void)fetchTrendListData{
    
    if ([self checkNetwork]) {
        return;
    }
    
    [YZClient fetchHomeTrendListWithSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"endRefreshing" object:nil];
            YZMHomeTrendModel *model = topModel.data;
            [_rankStrategyArray removeAllObjects];
            [_rankStrategyArray addObjectsFromArray:(NSArray *)model];
            [self tableset];
            [_masterTV reloadData];
        }
    } failure:^(NSError *error) {
       
        [error yz_showMessage];
    
    }];
}

- (BOOL)checkNetwork {
    
    if (kNetworkNotReachability) {
        self.hidden = YES;
        [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
        
        return YES;
    }
    self.hidden = NO;
    return NO;
}

-(void)tableset
{
    [_tradeTV mas_updateConstraints:^(MASConstraintMaker *make) {

        make.height.mas_equalTo(RankCellHeight * _rankUserArray.count);
    }];

    [_masterTV mas_updateConstraints:^(MASConstraintMaker *make) {

        make.height.mas_equalTo(60 * _rankStrategyArray.count);
    }];
    if (_index == 0) {
        self.frame = CGRectMake(10, _Y, ScreenWidth - 20, RankCellHeight * _rankUserArray.count + 60);
    } else {
        self.frame = CGRectMake(10, _Y, ScreenWidth - 20, 60 * _rankStrategyArray.count + 60);
    }
    
}

- (void)segmentView:(YZMSegmentView *)segmentView didScrollToIndexView:(NSInteger)index {
    _index = index;
    
    if (index == 0) {
        self.frame = CGRectMake(10, _Y, ScreenWidth - 20, RankCellHeight * _rankUserArray.count + 60);
    } else {
        self.frame = CGRectMake(10, _Y, ScreenWidth - 20, 60 * _rankStrategyArray.count + 60);
    }
    
    [self reloadView];
}

- (void)reloadView {
    if ([_delegate respondsToSelector:@selector(reloadView)]) {
        [_delegate reloadView];
    }
}

- (void)startTimer{

        
    if (!_rankTimer) {
        _rankTimer=[NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(fetchHomeTrendListData) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_rankTimer forMode:NSRunLoopCommonModes];
        [_rankTimer fire];
    }
    
}

- (void)stopTimer{

    if (_rankTimer) {
        
        if ([_rankTimer isValid]) {
            [_rankTimer invalidate];
        }
        _rankTimer = nil;
    }
    
}

-(void)fetchHomeTrendListData{
     
    if ([[YZMConfigureService sharedService] isInTradeTimePeriods]) {
        
        [self fetchTrendListData];
    }else{
        
        [_masterTV reloadData];
    }
}

@end
